package iit.projects.etaxi.model.dao;

import iit.projects.etaxi.model.entity.City;
import iit.projects.etaxi.model.entity.Sequence;
import iit.projects.etaxi.model.exception.CityNotFoundException;
import iit.projects.etaxi.model.exception.DuplicateCityException;
import iit.projects.etaxi.model.exception.DuplicateSequenceException;
import iit.projects.etaxi.model.exception.SequenceNotFoundException;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

@SuppressWarnings("unused")
public class HibernateSequenceDao extends HibernateDaoSupport implements SequenceDao {

	final Logger log = LoggerFactory.getLogger(HibernateCityDao.class);

	@Override
	public Sequence addSequence(Sequence sequence)
			throws DuplicateSequenceException {
		
		if(log.isDebugEnabled()){
			log.debug("Going to save Sequence : " + sequence.getSeqName());
		}
		Session session = getSession(false);
		
		try{
			Sequence duplicate = (Sequence)session.get(Sequence.class, sequence.getSeqName());
			if(duplicate != null){
				throw new DuplicateSequenceException(new String[]{sequence.getSeqName()});
			}
			return (Sequence)session.merge(sequence);
		}catch(HibernateException ex){
			throw convertHibernateAccessException(ex);
		}
	}

	@Override
	public void deleteSequence(Sequence sequence) {
		if (log.isDebugEnabled()) {
			log.debug("Deleting Sequence " + sequence.getSeqName());
		}
		Session session = getSession(false);
		try {
			session.delete(sequence);
		} catch (HibernateException ex) {
			throw convertHibernateAccessException(ex);
		}
	}

	@Override
	public Sequence findByPrimaryKey(String sequenceName)
			throws SequenceNotFoundException {

		if (log.isDebugEnabled()) {
			log.debug("Going to find Sequence by Name " + sequenceName);
		}
		
		Session session = getSession(false);
		try {
			Sequence sequence = (Sequence)session.get(Sequence.class, sequenceName);
			if(sequence == null){
				throw new SequenceNotFoundException();
			}
			return sequence;
		} catch (HibernateException ex) {
			throw convertHibernateAccessException(ex);
		}
	}

	@Override
	public Sequence updateSequence(Sequence sequence) {
		if (log.isDebugEnabled()) {
			log.debug("Updating Sequence " + sequence.getSeqName());
		}
		Session session = getSession(false);
		try {
			return (Sequence)session.merge(sequence);
		} catch (HibernateException ex) {
			throw convertHibernateAccessException(ex);
		}
	}
	
	
}
